<?php
namespace control;
/*
*模具转换类
*/

class moldChangeClass extends adIndexClass
{
    private const table = 'mold_change';
    private const page = 'moldChange';
    private const title = '模具转换';
    private const tableRecord = 'mold_inventory_record';
    public array $stateOption = ['草稿', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '转出模具',
                        'width' => 200,
                    ],
                    'model'         => [
                        'name'  => '规格型号',
                        'width' => 200,
                    ],
                    'outNum'          => [
                        'name'  => '数量',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'fee'          => [
                        'name'  => "费用（".static::$unit."）",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号"   => text(array("name" => "orderNo")),
                    "转出模具"   => text(array("name" => "moldName")),
                    "规格型号"   => text(array("name" => "model")),
                ],
                [
                    "单据日期" => text(['name' => 'createTime', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*行政人事-出差记录-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . $this->get('cla');
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*行政人事-出差记录-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            "state" => $this->post('state'),
        );
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );
        //初始化
        $and = "";
        $mAnd = '';
        if ($this->post('moldName')) {
            $mAnd = " and name like '%" . $this->post('moldName') . "%'";
        }
        if ($this->post('model')) {
            $mAnd = " and model like '%" . $this->post('model') . "%'";
        }
        if ($mAnd) {
            $and .= " and outMoldId in (select id from mold where coid = '" . self::$coid . "' {$mAnd})";
        }
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));

        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";

        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $outMold= query('mold', "id = '$array[outMoldId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'name':
                    case 'model':
                        $row[] = $outMold[$key];
                        break;
                    case 'outNum':
                        $row[] = self::lostZero($array['outNum'],'numPrecision');
                        break;
                    case 'fee':
                        $row[] = self::lostZero($array['fee']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(outNum),0) as outNum,ifnull(sum(fee),0) as fee",
        ]);
        $total    = [
            'outNum'        => self::formattingFigure($totalQuery['outNum'],'num'),
            'fee'        => self::formattingFigure($totalQuery['fee']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑
     *
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $outMoldName = moldClass::getName($info['outMoldId']);
        $inMoldName = moldClass::getName($info['inMoldId']);
        //表单
        $html = $this->layerEdit([
            "table" => [
                array(
                    must . "转出模具：" => hidden(array('name' => 'outMoldId', 'value' => $info['outMoldId'])) . "<span id='outMoldId' style='max-width: 80%;' class='exceed-ellipsis'>{$outMoldName}</span><span class='del-row-button' style='margin-left: 5px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','addMaterial',{type:'转出'})\">选择</span>",
                ),
                array(
                    must . "转出仓库：" => selectMultiple(["name" => "outWarehouseId", 'value'=>$info['outWarehouseId'],'table' => "warehouse", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'sqlField' => 'name', 'title' => '仓库名称']),
                    must . "转出数量：" => text(array('name'=>'outNum', 'other' => self::digitalFiltering('numPrecision'),'value'=>self::lostZero($info['outNum'],'numPrecision'))),
                ),
                array(
                    must . "转入模具：" => hidden(array('name' => 'inMoldId', 'value' => $info['inMoldId'])) . "<span id='inMoldId' style='max-width: 80%;' class='exceed-ellipsis'>{$inMoldName}</span><span class='del-row-button' style='margin-left: 5px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','addMaterial',{type:'转入'})\">选择</span>",
                ),
                array(
                    must . "转入仓库：" => selectMultiple(["name" => "inWarehouseId", 'value'=>$info['inWarehouseId'],'table' => "warehouse", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'sqlField' => 'name', 'title' => '仓库名称']),
                    must . "转入数量：" => text(array('name'=>'inNum', 'other' => self::digitalFiltering('numPrecision'),'value'=>self::lostZero($info['inNum'],'numPrecision'))),
                ),
                array(
                    '费用：' =>  text(array('name'=>'fee','unit'=>static::$unit, 'other' => self::digitalFiltering(),'value'=>self::lostZero($info['fee']))),
                    must . "单据日期：" => text(array("name" => "recordDate", 'laydate'=>[],"value" => $info['recordDate']?:$this->date)),
                ),
                array(
                    "备注：" => textarea(array("name" => "text", "value" => $info['text'])),
                ),
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $id)),
        ]);
        $html .= $this->js();
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

    public function js(): string
    {
        return <<<efo
<script>
          //选择生产产品
    function addMaterial(type='转出'){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMaterialEdit',$("form[name='mxForm']").serialize(),function(res) {
                 if (res.warn ==2){
                       $('#moldChangeAddMaterial').hide()
                     if (type =='转出'){
                      
                         console.log(res.name)
                           $("[name='outMoldId']").val(res.targetId);
                           $("#outMoldId").html(res.name)
                     }else{
                         $("[name='inMoldId']").val(res.targetId);
                         $("#inMoldId").html(res.name)
                     }
                 }else{
                     msg(res.warn);
                 }
            },'json');
    }
</script>
efo;
    }

    /*编辑*/
    public function editEdit()
    {

        $id = $this->post('id') ?: self::getId();
        //赋值
        $field = array(
            "outMoldId" => $this->post('outMoldId'),
            "inMoldId" => $this->post('inMoldId'),
            "outWarehouseId" => $this->post('outWarehouseId'),
            'inWarehouseId' => $this->post('inWarehouseId'),
            "outNum" => $this->post('outNum'),
            "inNum" => $this->post('inNum'),
            "fee" => $this->post('fee'),
            "recordDate" => $this->post('recordDate'),
            "text" => $this->post('text'),
        );
        $annotation = [
            "outMoldId" => '转出模具',
            'inMoldId' => '转入模具',
            "outWarehouseId" => '转出仓库',
            "inWarehouseId" => '转入仓库',
            "outNum" => '转出数量',
            "inNum" => '转入数量',
            "recordDate" => '日期',
        ];
        $rules = [
            "outMoldId" => 'required',
            'inMoldId' => 'required',
            "outWarehouseId" => 'required',
            "inWarehouseId" => 'required',
            "outNum" =>'required|numeric',
            "inNum" =>'required|numeric',
            "recordDate" => 'required|date',
        ];

        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "权限不足";
        } elseif ($info['state'] == '已确认') {
            $json['warn'] = '此单据已确认，不能编辑';
        } else {
            if (empty($info['id'])) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'MJZH' . date('Ymd',strtotime($field['recordDate'])),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, array("id" => $id, 'coid' => self::$coid, 'orderNo' => $userNo, 'state' => '草稿', 'stid' => $this->control['stid']));
                $json['warn'] = insert(array("table" => self::table, "field" => $field));
            } else {
                $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            }

            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }

        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        resp:
        return json_encode($json, 320);
    }


    /*出差详情*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = '未找到此' . self::title;
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($info['id'])) {
                $html = "未找到此记录";
            } else {
                //菜单
                $data = array(
                    "id" => $info['id'],
                );

                $button = [];
                if ($info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                if ($info['state'] != '已确认') {
                    if ($this->power(self::page, "edit")) {
                        //按钮
                        $button[] = [
                            "name" => "编辑",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "edit",
                            "post" => ["id" => $info['id']],
                        ];
                    }
                    if ($this->power(self::page, "del")) {
                        //按钮
                        $button[] = [
                            "name" => "删除",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'del', "id" => $info['id']],
                        ];
                    }
                }

                if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                    $button[] = [
                        "name" => "确认",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'confirm', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
//                if ($this->power(self::page, "confirm") && $info['state'] == '已确认') {
//                    $button[] = [
//                        "name" => "撤回",
//                        "type" => "弹出层",
//                        "cla" => $this->get('cla'),
//                        "fun" => "operate",
//                        "post" => ["act" => 'cancel', "id" => $info['id']],
//                    ];
//                }
                //操作记录
                $button[] = self::operateLogBut($info['id']);

                $outWarehouse = query('warehouse',"id = '$info[outWarehouseId]'");
                $inWarehouse = query('warehouse',"id = '$info[inWarehouseId]'");
                //生成表单
                $data['button'] = $this->tableShowButton($button);
                $data['html'] = $this->tableShow(array(
                    "基本信息" => array(
                        array(
                            "转出模具" =>  moldClass::getName($info['outMoldId']),
                            '转出仓库' => $outWarehouse['name'],
                            "转出数量" =>self::lostZero($info['outNum'],'numPrecision'),
                            "转入模具"=> moldClass::getName($info['inMoldId']),
                        ),
                        array(
                            "转入仓库" => $inWarehouse['name'],
                            "转入数量" => self::lostZero($info['inNum'],'numPrecision'),
                            "费用" => self::lostZero($info['fee']),
                            "单据日期" => $info['recordDate'],
                        ),
                        array(
                            '单据编号'=>$info['orderNo'],
                            "制单人" => self::findStaff($info['stid']),
                            "状态" => $info['state']
                        ),
                        array(
                            "备注" => pre($info['text']),
                        ),
                    ),
                ));
                //生成页面
                $html = $this->tab($data);
            }
        }
        //返回
        return $html;
    }


    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time,
        ];

        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此' . self::title;
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此' . self::title . '不是待确认状态，不能确认';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));

            $warn = static::insert([
                'table' => self::tableRecord,
                'field' => [
                    'id'            => self::getNo(),
                    'coid'          => self::$coid,
                    'warehouseId'   => $info['outWarehouseId'],
                    'mdid'          => $info['outMoldId'],
                    'num'           => -$info['outNum'],
                    'inventoryId'   => $info['id'],
                    'inventoryMxId' => '',
                ],
            ]);
            if ($warn !='新增成功'){
                $json['warn'] = '添加模具出库记录失败';
            }
            $warn = static::insert([
                'table' => self::tableRecord,
                'field' => [
                    'id'            => self::getNo(),
                    'coid'          => self::$coid,
                    'warehouseId'   => $info['inWarehouseId'],
                    'mdid'          => $info['inMoldId'],
                    'num'           => $info['inNum'],
                    'inventoryId'   => $info['id'],
                    'inventoryMxId' => '',
                ],
            ]);
            if ($warn !='新增成功'){
                $json['warn'] = '添加模具入库记录失败';
            }


            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //生成出库单
                auditingFollow(array(
                    "type" => "模具转换",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】确认",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name'],
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '确认成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此模具转换';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此模具转换不是已确认状态，无需撤回';
        }else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "模具转换",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】撤回",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name'],
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '撤回成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此模具转换';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此模具转换不是草稿状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "模具转换",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】提交",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name'],
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     *选择模具
     *
     * @return bool|string
     */
    public function addMaterial(): bool|string
    {
        $html =
            text(["name" => "type", "title" => "分类",]) .
            text(["name" => "code", "title" => "模具编码"]) .
            text(["name" => "moldName", "title" => "模具名称"]) .
            text(["name" => "model", "title" => "规格型号"]);
        $button = "<input style='margin-left: 5px' onclick=\"addMaterial('".$this->post('type')."')\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     *添加物料
     */
    public function addMaterialSearch(): bool|string
    {
        $like = [
            'name'  => $this->post('moldName'),
            'code'  => $this->post('code'),
            'model' => $this->post('model'),
            'type'  => $this->post('type'),
        ];
        $equal = [
            'state' =>'启用',
            'coid' => self::$coid,
        ];

        $where = search(["like" => $like, "=" => $equal]);
        $page = $this->page([
            "table" => "mold",
            "where" => $where,
            'pageNum' => 50,
            "order" => "time desc",
        ]);
        //获取表头
        $tr[] = ['', '分类', '编码', '模具名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[] = array(
                "<input name='mxId' value='$array[id]' type='radio' class='radio-bigger'>",
                $array['type'],
                $array['code'],
                $array['name'],
                $array['model'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMaterialEdit(): bool|string
    {
        $id = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        }elseif (empty($id)) {
            $json['warn'] = '请选择模具或设备';
        }  else {
            $mold = query('mold', "id = '$id' ");
            $json = [
                'warn' => 2,
                'name'     => moldClass::getName($id),
                'targetId' => $mold['id'],
            ];
        }
        return json_encode($json, 320);
    }

}
